package com.gmail.mariska.martin.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.gmail.mariska.martin.jpa.Pertask;
import com.gmail.mariska.martin.jpa.PertaskCommand;
import com.gmail.mariska.martin.jpa.dao.BankAccountDAO;
import com.gmail.mariska.martin.model.BankAccount;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.Service;

public class DepositeAccountService extends AbstractScheduledService {
	static final Logger logger = Logger.getLogger(DepositeAccountService.class);
	private final Service perzistenceService;

	public DepositeAccountService(Service perzistenceService) {
		this.perzistenceService = perzistenceService;
	}

	@Override
	protected void startUp() throws Exception {
		logger.info("startUp");
		perzistenceService.startAndWait();
		logger.info("perzistence is ready");
	}

	@Override
	protected void runOneIteration() throws Exception {
		Pertask.getInstance().transactionForWrite(new PertaskCommand<Boolean>() {
			@Override
			public Boolean execute(Pertask pertask) {
				BankAccountDAO dao = new BankAccountDAO(pertask.getEntityManager());
				List<BankAccount> findAll = dao.findAll();
				for (BankAccount bankAccount : findAll) {
					bankAccount.setValue(bankAccount.getValue() + 1);
					dao.update(bankAccount);
					logger.info("updating " + bankAccount);
				}
				return true;
			}
		});
	}

	@Override
	protected Scheduler scheduler() {
		return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.SECONDS);
	}

}
